package com.legal.controller.user;

import com.legal.domain.result.Result;
import com.legal.enums.CaptchaExceptionMsgEnums;
import com.legal.exception.CaptchaException;
import com.legal.service.user.CaptchaService;
import com.legal.service.user.RateLimitService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

/**
 * 验证码控制器
 */
@Tag(name = "验证码")
@RestController
@RequestMapping("/captcha")
@RequiredArgsConstructor
public class CaptchaController {

    // 验证码服务
    private final CaptchaService captchaService;

    // 滑动窗口限流服务
    private final RateLimitService rateLimitService;

    @Operation(summary = "获取验证码")
    @PostMapping
    /**
     * 获取验证码接口
     * 该方法用于生成并发送验证码到指定的电话号码
     * 同时，它实现了基于IP、设备ID和电话号码的多维度滑动窗口限流机制
     *
     * @param phoneNumber 用户的电话号码，用于接收验证码
     * @param request HTTP请求对象，用于获取请求的IP地址和设备ID
     * @return 返回包含验证码的Result对象
     * @throws CaptchaException 如果验证码生成或发送失败，抛出此异常
     */
    public Result<String> getCaptcha(@RequestParam String phoneNumber, HttpServletRequest request) {
        // 1.获取请求的IP地址和设备ID(设备“指纹”)
        String ip = request.getRemoteAddr();
        String deviceId = request.getHeader("Device-Id");

        // 2. 多维度滑动窗口限流
        // IP级别: 每分钟最多3次


        if (!rateLimitService.checkSlidingRateLimit("captcha:ip:" + ip, 3, Duration.ofMinutes(1))) {
            throw new CaptchaException(CaptchaExceptionMsgEnums.CAPTCHA_REQUEST_TOO_FREQUENT);
        }
         /*  工具类测试
         RateLimitUtils rateLimitUtils = new RateLimitUtils(redisTemplate);
        if (!rateLimitUtils.checkSlidingRateLimit("captcha:ip:" + ip, 3, Duration.ofMinutes(1))) {
            throw new CaptchaException(CaptchaExceptionMsgEnums.CAPTCHA_REQUEST_TOO_FREQUENT);
        }*/

        // 设备级别: 每小时最多5次
        if (deviceId != null && !rateLimitService.checkSlidingRateLimit(
                "captcha:device:" + deviceId, 5, Duration.ofHours(1))) {
            throw new CaptchaException(CaptchaExceptionMsgEnums.CAPTCHA_DEVICE_LIMIT_EXCEEDED);
        }

        // 手机号级别: 每24小时最多10次
        if (!rateLimitService.checkSlidingRateLimit(
                "captcha:phone:" + phoneNumber, 10, Duration.ofHours(24))) {
            throw new CaptchaException(CaptchaExceptionMsgEnums.CAPTCHA_PHONE_LIMIT_EXCEEDED);
        }

        // 生成并获取验证码
        String captcha =captchaService.getCaptcha(phoneNumber);
        // 返回包含验证码的结果
        return Result.ok(captcha);
    }
}
